package com.lucifer.cloud.boot.blog.util.operate;

import com.lucifer.cloud.boot.blog.config.UserSystem;
import com.lucifer.cloud.boot.blog.domin.type.BlogConstant;
import com.lucifer.cloud.commons.model.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Map;
import java.util.Objects;

/**
 * @author lucifer
 * @date 2024/1/23 13:37
 */
@Slf4j
@Aspect
@Component
public class OperatePermissionAspect {


    @Resource
    private UserSystem userSystem;

    @Pointcut("@annotation(com.lucifer.cloud.boot.blog.util.operate.OperatePermission)")
    public void operatePermission() {
    }

    @Around("operatePermission()")
    public Object around(ProceedingJoinPoint joinPoint) throws Exception {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (Objects.nonNull(attributes)) {
                HttpServletRequest request = attributes.getRequest();
                Long userId = userSystem.userId(request);
                if (Objects.isNull(userId)) {
                    return Result.error(HttpStatus.UNAUTHORIZED.value(), BlogConstant.NOT_LOGIN);
                }
                Map<String, String[]> parameterMap = request.getParameterMap();
                if (Objects.nonNull(parameterMap.get(BlogConstant.USER_ID))) {
                    String parameterUserId = parameterMap.get(BlogConstant.USER_ID)[0];
                    Long $userId = Long.parseLong(parameterUserId);
                    if (Objects.equals(userId, $userId)) {
                        return joinPoint.proceed();
                    }
                }
            }
            return Result.error(HttpStatus.METHOD_NOT_ALLOWED.value(), BlogConstant.NOT_PERMISSION);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}
